#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:HeWenjun
# datetime:2023/11/17 16:30
# software: PyCharm

from docx import Document


def replace_keyword(keyword, file_path, replacement):
    """
    word文档，按关键字查找替换文本
    :param keyword: 需要寻找的关键字
    :param file_path: 需要寻找的文档路径
    :param replacement: 替换后的最终文本
    :return:
    """
    # 打开Word文档
    doc = Document(file_path)
    # 遍历文档中的每个段落
    for paragraph in doc.paragraphs:
        # 如果关键字在段落中
        if keyword in paragraph.text:
            # 替换关键字
            paragraph.text = paragraph.text.replace(keyword, replacement)
            print(keyword + ' 已修改 ' + replacement)
    # 遍历文档中的每个表格
    for table in doc.tables:
        # 遍历表格中的每一行
        for row in table.rows:
            # 遍历行中的每一个单元格
            for cell in row.cells:
                # 如果关键字在单元格中
                if keyword in cell.text:
                    # 替换关键字
                    cell.text = cell.text.replace(keyword, replacement)
                    print(keyword + ' 已修改 ' + replacement)
    # 保存修改后的文档
    doc.save(file_path)


if __name__ == '__main__':
    file_path = '../output/咪咕总部平台运营技术中心公文功能测试报告5.73.0.docx'
    keyword = '123'
    replacement = '5.37.0'
    replace_keyword(keyword=keyword, file_path=file_path, replacement=replacement)